<%@ page language="java" pageEncoding="utf-8"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.File"%>
<%@ page import="java.io.FileFilter"%>
<%@ page import="java.text.DateFormat"%>
<%@ page import="org.jawa.util.Log"%>
<%@ page import="org.jawa.util.ParamUtils"%>
<%@ page import="org.jawa.util.JawaGlobals"%>
<%@ page import="org.apache.commons.io.filefilter.WildcardFileFilter"%>
<%@ page import="org.apache.commons.io.FileUtils"%>
<%@page import="org.apache.commons.lang.StringUtils"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.io.FileInputStream"%>
<jsp:useBean id="webManager" class="org.jawa.util.WebManager" />
<%
	webManager.init(request, response, session, application, out);
	String path = request.getContextPath();
%>
<%! 
    static final String ERROR = "error";
	static final String INFO = "info";
	static final String WARN = "warn";
	static final String DEBUG = "debug";
	static final String DEFAULT = DEBUG;

	static final String ASCENDING = "asc";
	static final String DESCENDING = "desc";

	static final String[] LINES = { "50", "100", "250", "500" };

	static final String[] REFRESHES = { "10", "30", "60", "90" };
	static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd kk:mm:ss");

	private static String parseDate(String input) {
		if (input == null || "".equals(input)) {
			return input;
		}
		if (input.length() < 19) {
			return input;
		}
		String d = input.substring(0, 19);
		// try to parse it
		try {
			StringBuffer buf = new StringBuffer(input.length());
			synchronized (formatter) {
				Date date = formatter.parse(d);
				buf.append("<span class=\" label \" title=\"").append(formatter.format(date)).append("\">");
			}
			buf.append(d).append("</span>");
			buf.append(input.substring(19, input.length()));
			return buf.toString();
		} catch (Exception pe) {
			return input;
		}
	}

	private static String hilite(String input) {
		if (input == null || "".equals(input)) {
			return input;
		}
		if (input.indexOf("jawa") > -1) {
			StringBuffer buf = new StringBuffer();
			buf.append("<span class=\"label label-warning\">").append(input).append("</span>");
			return buf.toString();
		}
		return input;
	}%>
	<%
		File logDir = new File(JawaGlobals.getHomeDirectory(), "logs");
		if (!logDir.exists()) {
			logDir.mkdirs();
		}
		String log = ParamUtils.getParameter(request, "log");
		if (null == log) {
			log = DEFAULT;
		}

		//读出所有的记录日志的天数
		List logDays = new ArrayList();
		FileFilter fileFilter = new WildcardFileFilter(log + ".log.*");
		File[] debugLogFiles = logDir.listFiles(fileFilter);
		
		logDays.add("最新");
		for (int i = 0; i < debugLogFiles.length; i++) {
			File debug = debugLogFiles[i];
			logDays.add(debug.getName().substring(debug.getName().lastIndexOf(".") + 1));
		}

		String logDay = ParamUtils.getParameter(request, "logDay");
		String numLinesParam = ParamUtils.getParameter(request, "lines");
		int numLines = ParamUtils.getIntParameter(request, "lines", 50);
		int refresh = ParamUtils.getIntParameter(request, "refresh", 10);
		String refreshParam = ParamUtils.getParameter(request, "refresh");
		String mode = ParamUtils.getParameter(request, "mode");
		boolean clearLog = ParamUtils.getBooleanParameter(request, "clearLog");
		boolean debugEnabled = ParamUtils.getBooleanParameter(request, "debugEnabled");
		boolean wasDebugEnabled = ParamUtils.getBooleanParameter(request, "wasDebugEnabled");

		// 打开或关闭DEBUG
		if (request.getParameter("wasDebugEnabled") != null && wasDebugEnabled != debugEnabled) {
			Log.setDebugEnabled(debugEnabled);
			response.sendRedirect(path + "/admin/server-log.jsp?log=debug");
			return;
		}

		// 设置默认
		if (log == null) {
			log = DEFAULT;
		}
		if (logDay == null) {
			logDay = "";
		}
		if (mode == null) {
			mode = ASCENDING;
		}
		if (numLinesParam == null) {
			numLinesParam = "50";
		}
		
		if("最新".equals(logDay)){
			logDay = "";
		}
		
		String filename = log + ".log."+ logDay ;
		File logFile = new File(logDir, filename);

		debugEnabled = Log.isDebugEnabled();

		if (clearLog && log != null) {
			if ("error".equals(log)) {
				Log.rotateErrorLogFile();
			} else if ("warn".equals(log)) {
				Log.rotateWarnLogFile();
			} else if ("info".equals(log)) {
				Log.rotateInfoLogFile();
			} else if ("debug".equals(log)) {
				Log.rotateDebugLogFile();
			}
			response.sendRedirect(path + "/admin/server-log.jsp?log=" + log);
			return;
		}

		//读取日志内容
		String lines[] = new String[0];
		int start = 0;
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(logFile), "GBK"));
			String line;
			int totalNumLines = 0;
			while ((line = in.readLine()) != null) {
				totalNumLines++;
			}
			in.close();
			// adjust the 'numLines' var to match totalNumLines if 'all' was passed in:
			if ("all".equals(numLinesParam)) {
				numLines = totalNumLines;
			}
			lines = new String[numLines];
			in = new BufferedReader(new InputStreamReader(new FileInputStream(logFile), "GBK"));
			// skip lines
			start = totalNumLines - numLines;
			if (start < 0) {
				start = 0;
			}
			for (int i = 0; i < start; i++) {
				in.readLine();
			}
			int i = 0;
			if ("asc".equals(mode)) {
				while ((line = in.readLine()) != null && i < numLines) {
					line = (line);
					line = parseDate(line);
					line = hilite(line);
					lines[i] = line;
					i++;
				}
			} else {
				int end = lines.length - 1;
				while ((line = in.readLine()) != null && i < numLines) {
					line = (line);
					line = parseDate(line);
					line = hilite(line);
					lines[end - i] = line;
					i++;
				}
			}
			numLines = start + i;
		} catch (Exception ex) {
			Log.info("无法打开日志文件.", ex);
		}
	%>
    <%
    	Date lastMod = new Date(logFile.lastModified());
    	DateFormat dateFormatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
    %>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>系统日志</title>
		<meta name="pageID" content="1105" />
		<%  if (refreshParam != null && !"无".equals(refreshParam)) { %>
		    <meta http-equiv="refresh" content="<%= refresh %>">
		<%  } %>
		<link rel="stylesheet" type="text/css" href="<%=path%>/styles/prettify.css">
		<style type="text/css">
			.hight {
				background: #DDDDDD;
			}
		</style>
	</head>
	<body>
		<div class="row-fluid">
			<ul class="breadcrumb">
				<li>
					您现在的位置:
				</li>
				<li>
					<a href="<%=path%>/admin/index.jsp">服务器</a>
				</li>
				<li>
					<span class="divider">/</span>
				</li>
				<li class="active">
					系统日志
				</li>
			</ul>
			<form action="<%=path%>/admin/server-log.jsp" id="logForm"
				method="post" class="">
				<input type="hidden" name="logDay" id="logDay" value="<%=logDay%>">
				<input type="hidden" name="log" id="log" value="<%=log%>">
				<input type="hidden" name="wasDebugEnabled"  value="<%=debugEnabled%>">
			    <ul class="nav nav-tabs">
					  <li class=" <%=(("debug".equals(log) ? "active" : ""))%> ">
					    <a href="#" onclick="changeLog('debug');">调试</a>
					  </li>
					  <li class=" <%=(("info".equals(log) ? "active" : ""))%> ">
					    <a href="#" onclick="changeLog('info');">信息</a>
					  </li>
					  <li class=" <%=(("warn".equals(log) ? "active" : ""))%> ">
					    <a href="#" onclick="changeLog('warn');">警告</a>
					  </li>
					  <li class=" <%=(("error".equals(log) ? "active" : ""))%> ">
					    <a href="#" onclick="changeLog('error');">错误</a>
					  </li>
					  <li class="dropdown pull-right" style="float: right;">
					      <a href="#" data-toggle="dropdown" class="dropdown-toggle"><%=dateFormatter.format(lastMod)%> <b class="caret"></b></a>
						  <ul class="dropdown-menu">
						     <%
						     	for (Iterator iter = logDays.iterator(); iter.hasNext();) {
						     		String day = (String) iter.next();
						     %>
								<li><a href="#" onclick="setLogDay('<%=day%>');"><%=day%></a></li>
							<%
								}
							%>
				          </ul>
					  </li>
			   </ul>
			<div class="tab-content ">
				<div class=" tab-pane fade in active">
					<div class="well">
						<strong >日志文件:</strong>
						<span ><%=logFile.getName()%><strong>(<%=FileUtils.byteCountToDisplaySize(logFile.length())%>)</strong></span>
						<input style="margin-left: 20px;" type="radio" name="mode" value="asc" <%=("asc".equals(mode) ? " checked" : "")%> onclick="this.form.submit();" id="rb01" />
						<strong >顺序</strong>
						<input type="radio" name="mode" value="desc" onclick="this.form.submit();" <%=("desc".equals(mode) ? " checked" : "")%> id="rb02" />
						<strong>颠倒</strong>
						<strong style="margin-left: 20px;">行数:</strong>
						<select name="lines"  onchange="this.form.submit();" style="width:70px;">
										<%
											for (String aLINES : LINES) {
												String selected = (aLINES.equals(numLinesParam)) ? " selected" : "";
										%>
										<option value="<%=aLINES%>" <%=selected%>><%=aLINES%></option>
										<%
												}
										%>
										<option value="all"
											<%=(("all".equals(numLinesParam)) ? " selected" : "")%>>
											所有
										</option>
						</select>
					</div>
				</div>	
			</div>
			<div class="scrollspy-example"  style="height:500px;overflow: auto;" >
				<pre class="prettyprint linenums"><ol class="linenums"><%
					for (String line1 : lines) {
						if (line1 != null) {
				%><li><%=line1%></li><%
					    }
					}
				%></ol></pre>
			</div>
			</form>	
		</div>
		
		<script src="<%=path%>/scripts/bootstrap.js"></script>
		<script src="<%=path%>/scripts/prettify.js"></script>
		<script>
			function setLog() {
				document.getElementById("clearLog").value = true;
			}
			function changeLog(obj) {
				document.getElementById("log").value = obj;
				document.getElementById("logForm").submit();
			}
			function setLogDay(obj) {
				document.getElementById("logDay").value = obj;
				document.getElementById("logForm").submit();
			}
		</script>
		
	</body>
</html>